﻿using System;
using System.Data;
using System.Data.OleDb;

namespace Testowanie
{
    public class DAL
    {
        private OleDbConnection connection = null;
        private OleDbDataAdapter dataAdapter = null;
        private OleDbCommandBuilder builder = null;

        public DAL(string sql, string connectionString)
        {
            connection = new OleDbConnection(connectionString);
            dataAdapter = new OleDbDataAdapter(new OleDbCommand(sql, connection));

            builder = new OleDbCommandBuilder(dataAdapter);
            dataAdapter.UpdateCommand = builder.GetUpdateCommand();
            dataAdapter.InsertCommand = builder.GetInsertCommand();
            dataAdapter.DeleteCommand = builder.GetDeleteCommand();

            Data = null;
        }

        public DataTable Data { get; private set; }

        public void Fill()
        {
            try
            {
                if (Data != null)
                    Data.Dispose();
                Data = new DataTable();

                connection.Open();
                dataAdapter.Fill(Data);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }

        public void SaveChanges()
        {
            try
            {
                if (Data != null)
                {
                    connection.Open();
                    dataAdapter.Update(Data);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }

        public void Dispose()
        {
            if (Data != null)
                Data.Dispose();
            if (dataAdapter != null)
                dataAdapter.Dispose();
            if (builder != null)
                builder.Dispose();
            if (connection != null)
                connection.Dispose();
        }
    }
}